import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_lang/flutter_lang.dart';
import 'package:flutter_theme/colors.dart';
import 'package:flutter_theme/theme.dart';
import 'package:flutter_theme/theme_utils.dart';
import 'package:lifecycle_monitor/lifecycle_monitor.dart';
import 'package:password_safety_keyboard/password_safety_keyboard.dart';
import 'package:route_manager/app_config.dart';
import 'package:route_manager/wx_navigator.dart';
import 'package:wallet_authentication/PIN/tools/generate_encrypt.dart';
import '../../module_config.dart';
import '../models/wallet_info_model.dart';
import '../widgets/shake_animation_widget.dart';
import '../widgets/snack_headtips_widget.dart';
// import '../widgets/number_keyborad_widget.dart';
import '../widgets/solidpoint_password_widget.dart';

class CheckPINPage extends StatefulWidget {
  final Map<String, dynamic> settingsMap;

  CheckPINPage({Key key, this.settingsMap}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _CheckPINPageState();
}

class _CheckPINPageState extends State<CheckPINPage> {
  String _checkNumber = '';
  bool _isHiddenBack;
  bool _isExitAPP = false;
  void Function(String value) _onCallBack;

  //final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

  @override
  void initState() {
    super.initState();

    /// 不设置默认显示
    _isHiddenBack = widget.settingsMap['isHiddenBack'];
    _onCallBack = widget.settingsMap['onCallBack'];
    _isExitAPP = widget.settingsMap['isExitAPP'];

    /// 验证PIN码特殊处理注销息屏逻辑
    StateObserver().removeObserver();
  }

  @override
  void dispose() {
    super.dispose();

    /// 验证PIN码特殊处理注册息屏逻辑
    StateObserver().registerObserver();
  }

  Widget getTipsWidget() {
    String descrip =
        '${WXLang.$t("authentication_inputOrigin_checkPin", package: ModuleConfig.moduleName)}';
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(vertical: 5),
      child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: EdgeInsets.symmetric(vertical: 10),
              child: Text(
                descrip,
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 16,color: WXTheme.$c("authentication_common_text_title")),
              ),
            ),
          ]),
    );
  }

  Widget getNumberKeyboradWidget() {
    return NumberKeyboradWidget(
        // isRandom: true,
        languageDelete:
            '${WXLang.$t("authentication_delete_keyboard", package: ModuleConfig.moduleName)}',
        backgroundColor: WXTheme.$c("authentication_number_keyboard_background"),
        onTap: (value) async {
          _checkNumber = value;

          setState(() {});
          if (_checkNumber.length != 6) {
            return;
          }
          String originalNum = await WalletInfo.getPinCodeName();
          if (originalNum == null || originalNum.length == 0) {
            /// 未设置或者为空字符串时不做操作
            return;
          }

          // if (_checkNumber.length == 6 && originalNum.length == 6) {
          // if (_checkNumber.length == 6) {
          if (GenerateEncrypt.generateMD5(_checkNumber) == originalNum) {
            if (_onCallBack != null) {
              _onCallBack('');
            }
          } else {
            /// 两次输入的内容不匹配逻辑添加
            SnackHeadTipsWidget.openSnackHeadTipsWidget(
                AppConfig.navigatorKey.currentState.overlay.context,
                '${WXLang.$t("authentication_diffCode_checkPin", package: ModuleConfig.moduleName)}');
            _checkNumber = '';
            _shakeAnimationController.start(shakeCount: 5);
          }
          // } else {
          //   /// 请继续输入
          // }

          print('onTap$value');
        });
  }

  static Future<void> popExitAPP() async {
    await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
  }

  /// 获取6个实心圆组件
  Widget getSolidpointPasswordWidget() {
    return Padding(
        padding: EdgeInsets.only(top: 90),
        child: SolidpointPasswordWidget(
          password: _checkNumber,
          inActiveColor: Colors.grey,
          activeColor: WXTheme.$c("authentication_tab_indicator_color")
        ));
  }

  ShakeAnimationController _shakeAnimationController =
      ShakeAnimationController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: WXTheme.$c("authentication_scaffold_color"),
      appBar: AppBar(
        backgroundColor: WXTheme.$c("authentication_header_background"),
        centerTitle: true,
        automaticallyImplyLeading: !_isHiddenBack,
        brightness: Brightness.dark,
        leading: _isHiddenBack
            ? null
            : IconButton(
                icon: Icon(
                  Icons.arrow_back,
                ),
                onPressed: () {
                  if (_isExitAPP != null && _isExitAPP) {
                    exit(0);
                  } else {
                    WXNavigator.pop(context: context);
                  }
                  // WXNavigator.pop(context: context);
                  // print('popExitAPP');
                  // exit(0);
                  // popExitAPP();
                }),
        title: Text(
          '${WXLang.$t("authentication_verifyCode_checkPin", package: ModuleConfig.moduleName)}',
            style: TextStyle(fontSize: 18, color:WXTheme.$c("authentication_header_icon_text")),
        ),
      ),
      body: Stack(
        children: <Widget>[
          Container(
            child: Column(
              children: <Widget>[
                getTipsWidget(),
                ShakeAnimationWidget(
                  child: getSolidpointPasswordWidget(),
                  isForward: false,
                  shakeCount: 5,
                  shakeRange: 0.2,
                  shakeAnimationController: _shakeAnimationController,
                ),
              ],
            ),
          ),
          Positioned(
            bottom: 0,
            child: getNumberKeyboradWidget(),
          )
        ],
      ),
    );
  }
}
